package com.example.testservicce;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.testservicce.service.MyBindService;

public class BindActivity extends AppCompatActivity implements View.OnClickListener{

    MyBindService.Agency agency;
    private MyConn conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind);
        Button btnBind= (Button) findViewById(R.id.btn_bind);
        Button btnUnBind= (Button) findViewById(R.id.btn_unbind);
        Button btnCall= (Button) findViewById(R.id.btn_call);
        btnBind.setOnClickListener(this);
        btnUnBind.setOnClickListener(this);
        btnCall.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_bind:
                //
                Intent intent=new Intent(getApplicationContext(), MyBindService.class);
                conn = new MyConn();
                bindService(intent, conn,BIND_AUTO_CREATE);
                Log.i("MyBindService", "funtionInService: bind服务 ");
                break;
            case R.id.btn_call:
                if (agency!=null) {
                    agency.work();
                }
                break;
            case R.id.btn_unbind:
                if (conn!=null){
                    unbindService(conn);
                }
                break;
        }
    }
    class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            agency= (MyBindService.Agency) service;
            Log.i("MyBindService", "funtionInService: 获取服务的中间人");

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
